using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Newtonsoft.Json;
using Microsoft.Security.Application;
using Microsoft.AspNet.Http;
using System.Web.WebSockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using Microsoft.AspNet.Http.Features;
using System.Net;
using System.Dynamic;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace CardWarWEB.Controllers
{
    [Route("Interesting")]
    public class InterestingController : Controller
    {

        private bool CheckLogin2()
        {

            if (string.IsNullOrEmpty(Request.Cookies["username"]) || string.IsNullOrEmpty(Request.Cookies["password"]))
                return false;
            else
            {
                string username = Request.Cookies["username"];
                string password = Request.Cookies["password"];
                if (!Conf.Users.ContainsKey(username))
                    return false;
                else
                {
                    string md5_password = Conf.Users[username].Password;
                    if (password.ToUpper() == md5_password.ToUpper())
                    {
                        List<string> flags = Conf.Users[username].Flags;
                        if (flags.Contains("login"))
                            return true;
                        else
                            return false;
                    }
                    else
                        return false;
                }
            }
        }

        private bool CheckLogin()
        {

            if (string.IsNullOrEmpty(Request.Cookies["gusername"]) || string.IsNullOrEmpty(Request.Cookies["gpassword"]))
                return false;
            else
            {
                string username = Request.Cookies["gusername"];
                string password = Request.Cookies["gpassword"];
                if (!Conf.Users.ContainsKey(username))
                    return false;
                else
                {
                    string md5_password = Conf.Users[username].Password;
                    if (password.ToUpper() == md5_password.ToUpper())
                    {
                        List<string> flags = Conf.Users[username].Flags;
                        if (flags.Contains("login"))
                        {
                            if (flags.Contains("game"))
                                return true;
                            else
                                return false;
                        }
                        else
                            return false;
                    }
                    else
                        return false;
                }
            }
        }

        [Route("CheckLogin")]
        [HttpPost]
        public object CheckLogin(string username, string password)
        {
            string Error = "未知错误";
            string state = "Error";
            if (string.IsNullOrEmpty(username))
                username = "";
            if (string.IsNullOrEmpty(password))
                password = "";
            if (username == "" || password == "")
            {
                Error = "登录失败！请填写正确的用户名和密码！";
            }
            else
            {
                if (Conf.Users.ContainsKey(username))
                {
                    UserConfig conf = Conf.Users[username];
                    if (conf.Password.ToUpper() == Server.MD5Encrypt(password).ToUpper())
                    {
                        List<string> flags = conf.Flags;
                        if (flags.Contains("login"))
                        {
                            if (flags.Contains("game"))
                            {
                                state = "Success";
                                Response.Cookies.Append("gusername", username);
                                Response.Cookies.Append("gpassword", Server.MD5Encrypt(password));
                            }
                            else
                            {
                                Error = "这个账号没有游戏权限！请联系管理员！";
                            }
                        }
                        else
                        {
                            Error = "这个账号没有登录权限！请联系管理员！";
                        }
                    }
                    else
                    {
                        Error = "登录失败！用户名或密码错误！";
                    }

                }
                else
                {
                    Error = "登录失败！用户名或密码错误！";
                }
            }
            Dictionary<string, string> ss = new Dictionary<string, string>()
            {
                { "state" , state},
                { "error" , Error }
            };

            string s = JsonConvert.SerializeObject(ss);
            return s;
        }

        [Route("MainGame")]
        public IActionResult MainGame()
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                if (CheckLogin2())
                    return View("QuickLogin");
                return View("LoginGame");
            }

            string username = Request.Cookies["gusername"];
            if (!Conf.Users[username].IsGameActivited)
                return View("CreatePlayer");

            ViewData.Add("Nick", Conf.Users[username].iG.Nick);
            ViewData.Add("UserName", username);
            ViewData.Add("Class", Conf.Users[username].iG.Class.ToString());
            ViewData.Add("Type", Conf.Users[username].iG.Type.ToString());
            return View();
        }

        public IActionResult Index()
        {
            return Redirect("/Interesting/MainGame");
        }

        [Route("LoginGame", Name = "LoginGame")]
        public IActionResult LoginGame()
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                if (CheckLogin2())
                    return View("QuickLogin");
                return View();
            }


            return Redirect("/Interesting/MainGame");
        }

        [Route("CreatePlayer", Name = "CreatePlayer")]
        public IActionResult CreatePlayer()
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                if (CheckLogin2())
                    return View("QuickLogin");
                return View("LoginGame");
            }
            return View();
        }

        [Route("Create")]
        [HttpPost]
        public object Create(string nick, string type)
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                return "请登录！";
            }
            if (string.IsNullOrEmpty(nick) || string.IsNullOrEmpty(type))
                return "请输入完整！并选择职业！";
            if (nick.Length > 16)
            {
                return "创建失败！名称过长！>16";
            }
            string username = Request.Cookies["gusername"];
            if (Conf.Users[username].IsGameActivited)
                return "不能再创建人物了！";

            int t = int.Parse(type);
            if (t < 0 || t > 3)
                return "职业选择错误！";

            iClasses icl = (iClasses)t;
            iGame Game = new iGame();
            Game.Nick = nick;
            Game.Username = username;
            Game.Class = icl;
            iSkill i = iSkill.Get(0);
            Game.Skills.Add(i.Hash, i);
            i = iSkill.Get(1);
            Game.Skills.Add(i.Hash, i);
            i = iSkill.Get(2);
            Game.Skills.Add(i.Hash, i);
            i = iSkill.Get(3);
            Game.Skills.Add(i.Hash, i);

            iItem I = iItem.Get(0);
            Game.Items.Add(I.Hash, I);
            Game.Player.胸甲 = I;

            I = iItem.Get(1);
            Game.Items.Add(I.Hash, I);
            Game.Player.鞋子 = I;

            I = iItem.Get(2);
            Game.Items.Add(I.Hash, I);
            Game.Player.腰带 = I;

            I = iItem.Get(3);
            Game.Items.Add(I.Hash, I);
            Game.Player.项链 = I;

            I = iItem.Get(4);
            Game.Items.Add(I.Hash, I);
            Game.Player.戒指1 = I;

            I = iItem.Get(5);
            Game.Items.Add(I.Hash, I);
            Game.Player.护手 = I;

            I = iItem.Get(6);
            I.Count = 5;
            Game.Items.Add(I.Hash, I);

            I = iItem.Get(7);
            I.Count = 3;
            Game.Items.Add(I.Hash, I);
            iiStatus iis = new iiStatus();
            iis.Name = "白银骑士的祝福(等级1)";
            iis.Description = "在受到即死伤害时，伤害减免1500点";
            iis.Round = -1;
            Game.Buff.Names = new Dictionary<string, iiStatus>() { { "白银骑士的祝福(等级1)", iis } };
            Game.Buff.白银骑士的祝福 = new ExpandoObject();
            Game.Buff.白银骑士的祝福.伤害减免 = 1500;
            Game.Buff.白银骑士的祝福.剩余时间 = -1;
            Game.Buff.白银骑士的祝福.等级 = 1;
            Conf.Users[username].IsGameActivited = true;
            Conf.Users[username].iG = Game;
            return "Success";
        }


        [Route("Connectx")]
        public async void Connectx()
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                string r = "请登录";

                await Response.Body.WriteAsync(Encoding.Default.GetBytes(r), 0, Encoding.Default.GetBytes(r).Length);
                return;
            }

            string username = Request.Cookies["gusername"];

            if (!Conf.Users[username].IsGameActivited)
            {
                string r = "你还没有激活游戏！";
                await Response.Body.WriteAsync(Encoding.Default.GetBytes(r), 0, Encoding.Default.GetBytes(r).Length);
                return;
            }
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                WebSocket x = await HttpContext.WebSockets.AcceptWebSocketAsync();

                while (true)
                {
                    if (x.State == WebSocketState.Open)
                    {
                        string state = "Error";
                        string message = "未知错误";
                        ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[16 * 1024]);
                        WebSocketReceiveResult result = await x.ReceiveAsync(buffer, CancellationToken.None);
                        Console.WriteLine("Count:" + result.Count);
                        if (result.Count <= 0)
                            goto End;

                        string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                        iGame ig = Conf.Users[username].iG;
                        #region 第一次登陆验证
                        if (userMsg == "test")
                        {
                            state = "Success";
                            if (Conf.onlines.Keys.Contains(username))
                            {
                                ArraySegment<byte> yi = new ArraySegment<byte>(Encoding.UTF8.GetBytes("anotherlogin"));
                                await Conf.onlines[username].WebSocket.SendAsync(yi, WebSocketMessageType.Text, true, CancellationToken.None);
                                Conf.errorexit.Add(username);
                                Conf.onlines[username].WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "出现了登录错误", CancellationToken.None);
                                Conf.onlines[username].WebSocket.Abort();
                                Conf.Users[username].iG.Status = iStatus.离线;
                                Conf.onlines.Remove(username);
                                state = "alreadyonline";
                            }
                            ig.Status = iStatus.在线;
                            Conf.onlines.Add(username, new OnlineStatus() { WebSocket = x });

                            message = "登录成功";
                            Dictionary<string, object> es = new Dictionary<string, object>() {
                                {"state",state }, { "message",message}, { "onlines",Conf.onlines.Count}
                            };
                            string se = JsonConvert.SerializeObject(es);
                            ArraySegment<byte> y = new ArraySegment<byte>(Encoding.UTF8.GetBytes(se));
                            await x.SendAsync(y, WebSocketMessageType.Text, true, CancellationToken.None);
                        }
                    #endregion

                    End:;

                    }
                    else
                    {
                        Console.WriteLine(x.State.ToString());
                        if (!Conf.errorexit.Contains(username))
                        {
                            Conf.Users[username].iG.Status = iStatus.离线;
                            Conf.onlines.Remove(username);
                        }
                        else
                            Conf.errorexit.Remove(username);



                        break;
                    }

                }
            }
            else
            {

                string r = "Success";

                await Response.Body.WriteAsync(Encoding.Default.GetBytes(r), 0, Encoding.Default.GetBytes(r).Length);

            }

        }

        [Route("C")]
        [HttpPost]
        public object C()
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                string r = "Error";
                return r;
            }

            string username = Request.Cookies["gusername"];

            if (!Conf.Users[username].IsGameActivited)
            {
                string r = "Error";
                return r;
            }

            iGame ig = Conf.Users[username].iG;
            Dictionary<int, object> it = new Dictionary<int, object>();
            long FireUP = 0;
            long IceUP = 0;
            long NaturalUP = 0;
            long WaterUP = 0;
            long LightUP = 0;
            long DarkUP = 0;
            long SpaceUP = 0;
            foreach (var ss in ig.Items.Values)
            {
                if (ss == Conf.Users[username].iG.Player.头部 ||
                    ss == Conf.Users[username].iG.Player.胸甲 ||
                    ss == Conf.Users[username].iG.Player.鞋子 ||
                    ss == Conf.Users[username].iG.Player.护手 ||
                    ss == Conf.Users[username].iG.Player.肩膀 ||
                    ss == Conf.Users[username].iG.Player.腿部 ||
                    ss == Conf.Users[username].iG.Player.腰带 ||
                    ss == Conf.Users[username].iG.Player.披风 ||
                    ss == Conf.Users[username].iG.Player.项链 ||
                    ss == Conf.Users[username].iG.Player.戒指1 ||
                    ss == Conf.Users[username].iG.Player.戒指2 ||
                    ss == Conf.Users[username].iG.Player.饰品1 ||
                    ss == Conf.Users[username].iG.Player.饰品2 ||
                    ss == Conf.Users[username].iG.Player.衬衣 ||
                    ss == Conf.Users[username].iG.Player.战袍)
                {

                    FireUP += ss.FireUP;
                    IceUP += ss.IceUP;
                    NaturalUP += ss.NaturalUP;
                    WaterUP += ss.WaterUP;
                    LightUP += ss.LightUP;
                    DarkUP += ss.DarkUP;
                    SpaceUP += ss.SpaceUP;
                    continue;
                }
                Dictionary<string, object> itt = new Dictionary<string, object>() {
                    { "ID" , ss.ID},
                    { "Hash",ss.Hash},
                    { "Name",ss.Name},
                     { "Note",ss.Note},
                      { "Description",ss.Description},
                       { "Type",ss.Type.ToString()},
                        { "Equips",ss.Equips.ToString()},
                         { "HP",ss.HP},
                          { "FireArmor",ss.FireArmor},
                           { "IceArmor",ss.IceArmor},
                            { "NaturalArmor",ss.NaturalArmor},
                             { "WaterArmor",ss.WaterArmor},
                              { "LightArmor",ss.LightArmor},
                               { "DarkArmor",ss.DarkArmor},
                               { "SpaceArmor",ss.SpaceArmor},
                              { "FireUP",ss.FireUP},
                           { "IceUP",ss.IceUP},
                            { "NaturalUP",ss.NaturalUP},
                             { "WaterUP",ss.WaterUP},
                              { "LightUP",ss.LightUP},
                               { "DarkUP",ss.DarkUP},
                               { "SpaceUP",ss.SpaceUP},
                            { "canSell",ss.canSell},
                             { "canDestroy",ss.canDestroy},
                              { "SellCost",ss.SellCost},
                               { "Level",ss.Level},
                                 { "SType",ss.SType.ToString()},
                    { "Class",ss.Class.ToString()},
                    { "Count",ss.Count}
                };
                it.Add(ss.Hash, itt);

            }
            Dictionary<int, object> ik = new Dictionary<int, object>();
            foreach (var ss in ig.Skills.Values)
            {
                string note = ss.Note;
                long DOWN = 0;
                long UP = 0;
                if (ss.isUP)
                {
                    if (ss.Properties == iSkill.iProperties.火焰)
                    {
                        DOWN = (ss.ATK + ss.DOWN + FireUP);
                        UP = (ss.ATK + ss.UP + FireUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.冰霜)
                    {
                        DOWN = (ss.ATK + ss.DOWN + IceUP);
                        UP = (ss.ATK + ss.UP + IceUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.自然)
                    {
                        DOWN = (ss.ATK + ss.DOWN + NaturalUP);
                        UP = (ss.ATK + ss.UP + NaturalUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.风水)
                    {
                        DOWN = (ss.ATK + ss.DOWN + WaterUP);
                        UP = (ss.ATK + ss.UP + WaterUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.光明)
                    {
                        DOWN = (ss.ATK + ss.DOWN + LightUP);
                        UP = (ss.ATK + ss.UP + LightUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.暗影)
                    {
                        DOWN = (ss.ATK + ss.DOWN + DarkUP);
                        UP = (ss.ATK + ss.UP + DarkUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.时空)
                    {
                        DOWN = (ss.ATK + ss.DOWN + SpaceUP);
                        UP = (ss.ATK + ss.UP + SpaceUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                }
                else
                {
                    DOWN = (ss.ATK + ss.DOWN + IceUP);
                    UP = (ss.ATK + ss.UP + IceUP);
                    note.Replace("%UP", UP.ToString());
                    note.Replace("%DOWN", DOWN.ToString());
                }

                Dictionary<string, object> ikk = new Dictionary<string, object>()
                {
                    { "ID" , ss.ID},
                    { "Hash",ss.Hash},
                    { "Name",ss.Name},
                     { "Note",note},
                      { "Type",ss.Type.ToString()},
                       { "SType",ss.SType.ToString()},
                        { "Class",ss.Class.ToString()},
                         { "Properties",ss.Properties.ToString()},
                          { "ATK",ss.ATK},
                          { "UP",UP},
                          { "DOWN",DOWN},
                             { "canLevelup",ss.canLevelup},
                              { "Level",ss.Level},
                               { "MaxLevel",ss.MaxLevel},
                               { "UpEXP",ss.UpEXP},
                            { "NowEXP",ss.NowEXP},
                             { "canPaid",ss.canPaid},
                              { "Paid",ss.Paid},
                               { "Cost",ss.Cost},
                    { "iClass",ss.iClass.ToString()},
                                        { "Show",ss.Show}
                };
                ik.Add(ss.Hash, ikk);
            }

            Dictionary<string, int?> p = new Dictionary<string, int?>() {
                   { "头部",ig.Player.头部?.Hash},
                   { "胸甲",ig.Player.胸甲?.Hash},
                   { "鞋子",ig.Player.鞋子?.Hash},
                   { "护手",ig.Player.护手?.Hash},
                   { "肩膀",ig.Player.肩膀?.Hash},
                   { "腿部",ig.Player.腿部?.Hash},
                   { "腰带",ig.Player.腰带?.Hash},
                   { "披风",ig.Player.披风?.Hash},
                   { "项链",ig.Player.项链?.Hash},
                   { "戒指1",ig.Player.戒指1?.Hash},
                   { "戒指2",ig.Player.戒指2?.Hash},
                   { "饰品1",ig.Player.饰品1?.Hash},
                   { "饰品2",ig.Player.饰品2?.Hash},
                   { "衬衣",ig.Player.衬衣?.Hash},
                   { "战袍",ig.Player.战袍?.Hash},
            };

            Dictionary<string, object> c = new Dictionary<string, object>() {
                { "Username",ig.Username},
                { "Nick",ig.Nick},
                { "Items",it},
                { "Player",p},
                { "Skills",ik},
                { "Type",ig.Type.ToString()},
                { "Status",ig.Status.ToString()},
                { "Coin",ig.Coin},
                { "Level",ig.Level},
                { "Exp",ig.Exp},
                { "ActivePoint",ig.ActivePoint},
                { "Class",ig.Class.ToString()},
                { "EXP",ig.Exp},
                { "NextEXP",iConf.GetLeastExps(ig.Level,ig.Exp)},
                { "Buff",ig.Buff.Names}


            };
            string s = JsonConvert.SerializeObject(c);
            return s;

        }

        [Route("SS")]
        [HttpPost]
        public object SS(string hash)
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                return "Error";
            }

            if (string.IsNullOrEmpty(hash))
                return "Error";

            string username = Request.Cookies["gusername"];

            if (!Conf.Users[username].IsGameActivited)
                return "Error";
            try
            {
                int i = int.Parse(hash);
                if (!Conf.Users[username].iG.Items.ContainsKey(i))
                    return "Error";
                var ss = Conf.Users[username].iG.Items[i];
                Dictionary<string, object> it = new Dictionary<string, object>() {
                    { "ID" , ss.ID},
                { "Hash",ss.Hash},
                    { "Name",ss.Name},
                     { "Note",ss.Note},
                      { "Description",ss.Description},
                       { "Type",ss.Type.ToString()},
                        { "Equips",ss.Equips.ToString()},
                         { "HP",ss.HP},
                          { "FireArmor",ss.FireArmor},
                           { "IceArmor",ss.IceArmor},
                            { "NaturalArmor",ss.NaturalArmor},
                             { "WaterArmor",ss.WaterArmor},
                              { "LightArmor",ss.LightArmor},
                               { "DarkArmor",ss.DarkArmor},
                               { "SpaceArmor",ss.SpaceArmor},
                          { "FireUP",ss.FireUP},
                           { "IceUP",ss.IceUP},
                            { "NaturalUP",ss.NaturalUP},
                             { "WaterUP",ss.WaterUP},
                              { "LightUP",ss.LightUP},
                               { "DarkUP",ss.DarkUP},
                               { "SpaceUP",ss.SpaceUP},
                            { "canSell",ss.canSell},
                             { "canDestroy",ss.canDestroy},
                              { "SellCost",ss.SellCost},
                               { "Level",ss.Level},
                { "SType",ss.SType.ToString()},
                { "Class",ss.Class.ToString()},
                    { "Count",ss.Count}


        };


                string s = JsonConvert.SerializeObject(it);
                return s;
            }
            catch (Exception)
            {
                return "Error";
            }
        }


        [Route("D")]
        [HttpPost]
        public object D(string pos)
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                return "Error";
            }

            if (string.IsNullOrEmpty(pos))
                return "Error";

            string username = Request.Cookies["gusername"];

            if (!Conf.Users[username].IsGameActivited)
                return "Error";

            if (pos == "toubu")
            {
                Conf.Users[username].iG.Player.头部 = null;
            }
            else if (pos == "xiongjia")
            {
                Conf.Users[username].iG.Player.胸甲 = null;
            }
            else if (pos == "xiezi")
            {
                Conf.Users[username].iG.Player.鞋子 = null;
            }
            else if (pos == "hushou")
            {
                Conf.Users[username].iG.Player.护手 = null;
            }
            else if (pos == "jianbang")
            {
                Conf.Users[username].iG.Player.肩膀 = null;
            }
            else if (pos == "tuibu")
            {
                Conf.Users[username].iG.Player.腿部 = null;
            }
            else if (pos == "yaodai")
            {
                Conf.Users[username].iG.Player.腰带 = null;
            }
            else if (pos == "pifeng")
            {
                Conf.Users[username].iG.Player.披风 = null;
            }
            else if (pos == "xianglian")
            {
                Conf.Users[username].iG.Player.项链 = null;
            }
            else if (pos == "jiezhi1")
            {
                Conf.Users[username].iG.Player.戒指1 = null;
            }
            else if (pos == "jiezhi2")
            {
                Conf.Users[username].iG.Player.戒指2 = null;
            }
            else if (pos == "shipin1")
            {
                Conf.Users[username].iG.Player.饰品1 = null;
            }
            else if (pos == "shipin2")
            {
                Conf.Users[username].iG.Player.饰品2 = null;
            }
            else if (pos == "chenyi")
            {
                Conf.Users[username].iG.Player.衬衣 = null;
            }
            else if (pos == "zhanpao")
            {
                Conf.Users[username].iG.Player.战袍 = null;
            }
            else
            {
                return "Error";
            }

            return "Success";

        }

        [Route("Des")]
        [HttpPost]
        public object Des(string hash, string c)
        {
            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                return "Error";
            }

            if (string.IsNullOrEmpty(hash))
                return "Error";

            if (string.IsNullOrEmpty(c))
                return "Error";

            string username = Request.Cookies["gusername"];

            if (!Conf.Users[username].IsGameActivited)
                return "Error";

            int cc = -2;
            try
            {
                cc = int.Parse(c);
            }
            catch (Exception)
            {
                return "Error";
            }

            if (cc < -1)
                return "Error";

            try
            {
                int h = int.Parse(hash);
                if (!Conf.Users[username].iG.Items.ContainsKey(h))
                    return "Error";

                iItem it = Conf.Users[username].iG.Items[h];
                if (it == Conf.Users[username].iG.Player.头部 ||
                    it == Conf.Users[username].iG.Player.胸甲 ||
                    it == Conf.Users[username].iG.Player.鞋子 ||
                    it == Conf.Users[username].iG.Player.护手 ||
                    it == Conf.Users[username].iG.Player.肩膀 ||
                    it == Conf.Users[username].iG.Player.腿部 ||
                    it == Conf.Users[username].iG.Player.腰带 ||
                    it == Conf.Users[username].iG.Player.披风 ||
                    it == Conf.Users[username].iG.Player.项链 ||
                    it == Conf.Users[username].iG.Player.戒指1 ||
                    it == Conf.Users[username].iG.Player.戒指2 ||
                    it == Conf.Users[username].iG.Player.饰品1 ||
                    it == Conf.Users[username].iG.Player.饰品2 ||
                    it == Conf.Users[username].iG.Player.衬衣 ||
                    it == Conf.Users[username].iG.Player.战袍)
                    return "Cant";

                int t = it.Count;
                if (cc == -1 || cc >= t)
                {
                    Conf.Users[username].iG.Items.Remove(h);
                    return "Success";
                }
                else
                {
                    it.Count -= cc;
                    return "Success";
                }
            }
            catch (Exception)
            {
                return "Error";
            }
        }

        [Route("U")]
        [HttpPost]
        public object U(string hash)
        {

            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                return "Error";
            }

            if (string.IsNullOrEmpty(hash))
                return "Error";


            string username = Request.Cookies["gusername"];

            if (!Conf.Users[username].IsGameActivited)
                return "Error";

            try
            {
                int h = int.Parse(hash);
                if (!Conf.Users[username].iG.Items.ContainsKey(h))
                    return "Error";

                if (Conf.Users[username].iG.Items[h].Type != iItem.iTypes.消耗品)
                    return "Cant";

                iItem i = Conf.Users[username].iG.Items[h];
                if (i.Count > 1)
                    i.Count--;
                else
                    Conf.Users[username].iG.Items.Remove(h);

                if (i.ID == 7)
                {
                    if (Conf.Users[username].iG.Buff.Names.ContainsKey(i.Name))
                    {
                        Conf.Users[username].iG.Buff.Names[i.Name].Round = 2;
                    }
                    else
                    {
                        iiStatus iis = new iiStatus();
                        iis.Name = "小型生命药水";
                        iis.Description = i.Description;
                        iis.Round = 2;
                        Conf.Users[username].iG.Buff.Names.Add(i.Name, iis);

                    }

                    Conf.Users[username].iG.Buff.小型生命药水 = new ExpandoObject();
                    Conf.Users[username].iG.Buff.小型生命药水.提升生命值 = 2500;
                    Conf.Users[username].iG.Buff.小型生命药水.剩余时间 = 2;
                }

                return "Success";
            }
            catch (Exception)
            {
                return "Error";
            }
        }


        [Route("E")]
        [HttpPost]
        public object E(string hash)
        {

            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                return "Error";
            }

            if (string.IsNullOrEmpty(hash))
                return "Error";


            string username = Request.Cookies["gusername"];

            if (!Conf.Users[username].IsGameActivited)
                return "Error";

            try
            {
                int h = int.Parse(hash);
                if (!Conf.Users[username].iG.Skills.ContainsKey(h))
                    return "Error";

                Conf.Users[username].iG.Skills[h].Show = !Conf.Users[username].iG.Skills[h].Show;
                return "Success";

            }
            catch (Exception)
            {
                return "Error";
            }
        }


        [Route("SSK")]
        [HttpPost]
        public object SSK(string hash)
        {

            if (!CheckLogin())
            {
                Server.RemoveCookie(this, "gusername");
                Server.RemoveCookie(this, "gpassword");
                return "Error";
            }

            if (string.IsNullOrEmpty(hash))
                return "Error";

            string username = Request.Cookies["gusername"];

            if (!Conf.Users[username].IsGameActivited)
                return "Error";
            try
            {
                int i = int.Parse(hash);
                if (!Conf.Users[username].iG.Skills.ContainsKey(i))
                    return "Error";

                long FireUP = 0;
                long IceUP = 0;
                long NaturalUP = 0;
                long WaterUP = 0;
                long LightUP = 0;
                long DarkUP = 0;
                long SpaceUP = 0;
                foreach (var sss in Conf.Users[username].iG.Items.Values)
                {
                    if (sss == Conf.Users[username].iG.Player.头部 ||
                        sss == Conf.Users[username].iG.Player.胸甲 ||
                        sss == Conf.Users[username].iG.Player.鞋子 ||
                        sss == Conf.Users[username].iG.Player.护手 ||
                        sss == Conf.Users[username].iG.Player.肩膀 ||
                        sss == Conf.Users[username].iG.Player.腿部 ||
                        sss == Conf.Users[username].iG.Player.腰带 ||
                        sss == Conf.Users[username].iG.Player.披风 ||
                        sss == Conf.Users[username].iG.Player.项链 ||
                        sss == Conf.Users[username].iG.Player.戒指1 ||
                        sss == Conf.Users[username].iG.Player.戒指2 ||
                        sss == Conf.Users[username].iG.Player.饰品1 ||
                        sss == Conf.Users[username].iG.Player.饰品2 ||
                        sss == Conf.Users[username].iG.Player.衬衣 ||
                        sss == Conf.Users[username].iG.Player.战袍)
                    {

                        FireUP += sss.FireUP;
                        IceUP += sss.IceUP;
                        NaturalUP += sss.NaturalUP;
                        WaterUP += sss.WaterUP;
                        LightUP += sss.LightUP;
                        DarkUP += sss.DarkUP;
                        SpaceUP += sss.SpaceUP;
                        continue;
                    }
                }



                var ss = Conf.Users[username].iG.Skills[i];
                string note = ss.Note;
                long DOWN = 0;
                long UP = 0;
                if (ss.isUP)
                {
                    if (ss.Properties == iSkill.iProperties.火焰)
                    {
                        DOWN = (ss.ATK + ss.DOWN + FireUP);
                        UP = (ss.ATK + ss.UP + FireUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.冰霜)
                    {
                        DOWN = (ss.ATK + ss.DOWN + IceUP);
                        UP = (ss.ATK + ss.UP + IceUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.自然)
                    {
                        DOWN = (ss.ATK + ss.DOWN + NaturalUP);
                        UP = (ss.ATK + ss.UP + NaturalUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.风水)
                    {
                        DOWN = (ss.ATK + ss.DOWN + WaterUP);
                        UP = (ss.ATK + ss.UP + WaterUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.光明)
                    {
                        DOWN = (ss.ATK + ss.DOWN + LightUP);
                        UP = (ss.ATK + ss.UP + LightUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.暗影)
                    {
                        DOWN = (ss.ATK + ss.DOWN + DarkUP);
                        UP = (ss.ATK + ss.UP + DarkUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                    else if (ss.Properties == iSkill.iProperties.时空)
                    {
                        DOWN = (ss.ATK + ss.DOWN + SpaceUP);
                        UP = (ss.ATK + ss.UP + SpaceUP);
                        note = note.Replace("%UP", UP.ToString());
                        note = note.Replace("%DOWN", DOWN.ToString());
                    }
                }
                else
                {
                    DOWN = (ss.ATK + ss.DOWN + IceUP);
                    UP = (ss.ATK + ss.UP + IceUP);
                    note.Replace("%UP", UP.ToString());
                    note.Replace("%DOWN", DOWN.ToString());
                }

                Dictionary<string, object> ikk = new Dictionary<string, object>()
                {
                    { "ID" , ss.ID},
                    { "Hash",ss.Hash},
                    { "Name",ss.Name},
                     { "Note",note},
                      { "Type",ss.Type.ToString()},
                       { "SType",ss.SType.ToString()},
                        { "Class",ss.Class.ToString()},
                         { "Properties",ss.Properties.ToString()},
                          { "ATK",ss.ATK},
                          { "UP",UP},
                          { "DOWN",DOWN},
                             { "canLevelup",ss.canLevelup},
                              { "Level",ss.Level},
                               { "MaxLevel",ss.MaxLevel},
                               { "UpEXP",ss.UpEXP},
                            { "NowEXP",ss.NowEXP},
                             { "canPaid",ss.canPaid},
                              { "Paid",ss.Paid},
                               { "Cost",ss.Cost},
                    { "iClass",ss.iClass.ToString()},
                                        { "Show",ss.Show}
                };

                return JsonConvert.SerializeObject(ikk);
            }
            catch (Exception)
            {
                return "Error";
            }


        }
    }


}
